package com.hc.file.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import com.hc.bean.AlarmBean;
import com.hc.bean.DeviceBean;
import com.hc.server.MapFileUtil;
import com.hc.time.util.DateUtil;
import com.hc.util.CommonData;

public class SaveHistoryFile {
	
	private static SaveHistoryFile saveHistoryFile;
	private String alarmFilePath = CommonData.systemPath + "config" + File.separator + MapFileUtil.ALARM_FILE + File.separator + "alarm.txt";
	
	private SaveHistoryFile(){
		
	}
	
	public static SaveHistoryFile getInstance(){
		if(saveHistoryFile == null)
			saveHistoryFile = new SaveHistoryFile();
		return saveHistoryFile;
	}
	
	public synchronized void writeDevPath(final DeviceBean bean){
		new Thread(){
			public void run() {
				String devFilePath = CommonData.systemPath + "config" + File.separator + MapFileUtil.PATH_FILE + File.separator + bean.getDeviceId() + ".txt";
				BufferedWriter writer = null;
				try {
					writer = new BufferedWriter(new FileWriter(new File(devFilePath), true));
					writer.write(analyDeviceBean(bean) + "\r\n");
					writer.flush();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						if (writer != null) {
							writer.close();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			};
		}.start();
	}
	
	private String analyDeviceBean(DeviceBean bean){
		StringBuffer sb = new StringBuffer();
		sb.append(DateUtil.getNowTimeStringByHour());
		sb.append(" ");
		sb.append(bean.getX());
		sb.append(" ");
		sb.append(bean.getY());
		sb.append(" ");
		sb.append(bean.getZ());
		return sb.toString();
	}
	
	public synchronized void writeHistoryAlarm(final AlarmBean bean){
		new Thread(){
			public void run(){
				BufferedWriter writer = null;
				try {
					writer = new BufferedWriter(new FileWriter(new File(alarmFilePath), true));
					writer.write(analyAlarmBean(bean) + "\r\n");
					writer.flush();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						if (writer != null) {
							writer.close();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
	
	private String analyAlarmBean(AlarmBean bean){
		StringBuffer sb = new StringBuffer();
		sb.append(bean.getTime());
		sb.append(" ");
		sb.append(bean.getDevType());
		sb.append(" ");
		sb.append(bean.getDevId());
		sb.append(" ");
		sb.append(bean.getContent());
		return sb.toString();
	}
}
